package com.blog4j.article.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.blog4j.api.vo.UserIllegalRecordVo;
import com.blog4j.article.entity.ArticleVerifyRecordEntity;
import com.blog4j.article.mapper.ArticleVerifyRecordMapper;
import com.blog4j.common.constants.CommonConstant;
import com.blog4j.common.enums.ArticleVerifyContentTypeEnum;
import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.enums.UserIllegalTypeEnum;
import com.blog4j.common.enums.VerifyStatusEnum;
import com.blog4j.common.enums.YesOrNoEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.common.model.LogVo;
import com.blog4j.common.utils.CommonUtil;
import com.blog4j.contentVerify.constants.VerifyConstants;
import com.blog4j.contentVerify.context.ContentVerifyContext;
import com.blog4j.contentVerify.context.VerifyResult;
import com.blog4j.contentVerify.enums.TextServiceEnum;
import com.blog4j.contentVerify.enums.VerifyResultEnum;
import com.blog4j.contentVerify.enums.VerifyTypeEnum;
import com.blog4j.contentVerify.model.TextVerifyModel;
import com.blog4j.contentVerify.processor.VerifyProcessor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/7/23 21:33
 **/
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class AsyncService {
    private final ApiCallService apiCallService;
    private final VerifyProcessor verifyProcessor;
    private final ArticleVerifyRecordMapper articleVerifyRecordMapper;

    /**
     * 当分类名称修改后，同步更新文章信息中的分类信息
     *
     * @param categoryId 分类ID
     * @param categoryName 分类名称
     */
    @Async("customExecutor")
    public void updateArticleCategoryName(String categoryId, String categoryName) {
        /*LambdaQueryWrapper<ArticleEntity> wrapper = new LambdaQueryWrapper<ArticleEntity>()
                .eq(ArticleEntity::getCategoryId, categoryId);
        List<ArticleEntity> articleList = this.baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(articleList)) {
            return;
        }
        for (ArticleEntity article : articleList) {
            article.setCategoryName(categoryName);
        }
        articleMapper.update()
        articleService.updateBatchById(articleList);*/
    }

    /**
     * 当分类名称修改后，同步更新文章信息中的标签信息
     *
     * @param labelId 标签ID
     * @param labelName 标签名称
     */
    @Async("customExecutor")
    public void updateArticleLabelName(String labelId, String labelName) {
        /*LambdaQueryWrapper<ArticleEntity> wrapper = new LambdaQueryWrapper<ArticleEntity>()
                .eq(ArticleEntity::getLabelId, labelId);
        List<ArticleEntity> articleList = articleService.list(wrapper);
        if (CollectionUtil.isEmpty(articleList)) {
            return;
        }
        for (ArticleEntity article : articleList) {
            article.setLabelName(labelName);
        }
        articleService.updateBatchById(articleList);*/
    }

    /**
     * 发送邮件给文章审批人
     *
     * @param email 接收方邮件地址
     * @param userName 接收方用户名称
     */
    @Async("customExecutor")
    public void sendSystemEmailToArticleApproveUser(String email, String userName) {
        if (StringUtils.isBlank(email) || StringUtils.isBlank(userName)) {
            return;
        }
        apiCallService.sendSystemEmailToArticleApproveUser(email, userName);
    }

    /**
     * 发送邮件给文章审批人
     *
     * @param email 接收方邮件地址
     * @param articleTitle 文章标题
     */
    @Async("customExecutor")
    public void sendSystemEmailToArticleCreater(String email, String articleTitle) {
        if (StringUtils.isBlank(email) || StringUtils.isBlank(articleTitle)) {
            return;
        }
        apiCallService.sendSystemEmailToArticleCreater(email, articleTitle);
    }

    /**
     * 异步添加日志信息
     *
     * @param logVo 日志信息
     */
    @Async("customExecutor")
    public void addLog(LogVo logVo) {
        apiCallService.addLog(logVo);
    }

    /**
     * 异步添加用户不合法的行为
     *
     * @param userId 用户ID
     */
    @Async("customExecutor")
    public void addUserIllegalRecord(String userId) {
        UserIllegalRecordVo recordVo = UserIllegalRecordVo.builder()
                .userId(userId)
                .illegalType(UserIllegalTypeEnum.ILLEGAL_COMMENT.getType())
                .createTime(CommonUtil.getCurrentDateTime())
                .build();
        apiCallService.addUserIllegalRecord(recordVo);
    }

    /**
     * 检查文章内容
     *
     * @param articleContent 文章内容
     * @param articleId 文章ID
     * @param userId 用户ID
     */
    @Async("customExecutor")
    public void checkArticleContent(String articleContent, String articleId, String userId) {
        if (articleContent.length() <= VerifyConstants.TEXT_LENGTH) {
            if (!doCheckArticleContent(articleContent, articleId, userId)) {
                addUserIllegalRecord(userId);
            }
            return;
        }

        List<String> articleContentList = CommonUtil.sliceStr(articleContent, VerifyConstants.TEXT_LENGTH);
        if (CollectionUtil.isEmpty(articleContentList)) {
            return;
        }

        for (String content : articleContentList) {
            if (!doCheckArticleContent(content, articleId, userId)) {
                addUserIllegalRecord(userId);
                return;
            }
        }
    }

    private boolean doCheckArticleContent(String articleContent, String articleId, String userId) {
        boolean checkResult = Boolean.TRUE;
        if (StringUtils.isBlank(articleContent) || StringUtils.isBlank(userId)) {
            return true;
        }
        VerifyResult verifyResult = this.getVerifyResult(articleContent);
        // 获取阿里云内容审核接口失败 重试三次
        if (!verifyResult.getStatus()) {
            try {
                int retryTime = 0;
                while(retryTime < CommonConstant.DEFAULT_RETRY_TIMES) {
                    verifyResult = this.getVerifyResult(articleContent);
                    if (verifyResult.getStatus()) {
                        break;
                    }
                    ThreadUtil.sleep(CommonConstant.DEFAULT_RETRY_INTERVAL_TIME);
                    retryTime += 1;
                }

                if (!verifyResult.getStatus()) {
                    // 重试了三次还是调用失败
                    ArticleVerifyRecordEntity articleVerifyRecord = new ArticleVerifyRecordEntity();
                    articleVerifyRecord.setVerifyContent(articleContent)
                            .setContentType(ArticleVerifyContentTypeEnum.ARTICLE_CONTENT.getType())
                            .setUserId(userId)
                            .setArticleId(articleId)
                            .setNeedManualVerify(YesOrNoEnum.YES.getCode())
                            .setVerifyStatus(VerifyStatusEnum.WAIT.getStatus());
                    articleVerifyRecordMapper.insert(articleVerifyRecord);
                    return true;
                }
            } catch (Exception exception) {
                log.error("checkArticleContent error .");
                throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
            }
        }

        VerifyResultEnum result = verifyResult.getResult();
        if (result == VerifyResultEnum.PASS) {
            return Boolean.TRUE;
        }
        ArticleVerifyRecordEntity articleVerifyRecord = new ArticleVerifyRecordEntity();
        articleVerifyRecord.setVerifyContent(articleContent)
                .setContentType(ArticleVerifyContentTypeEnum.ARTICLE_CONTENT.getType())
                .setUserId(userId)
                .setArticleId(articleId)
                .setVerifyStatus(VerifyStatusEnum.VERIFIED.getStatus())
                .setVerifyType(com.blog4j.common.enums.VerifyTypeEnum.MACHINE.getType())
                .setNeedManualVerify(YesOrNoEnum.NO.getCode())
                .setVerifyResult(VerifyResultEnum.PASS.getDesc())
                .setVerifyTime(CommonUtil.getCurrentDateTime());
        if (result == VerifyResultEnum.IN_DOUBT) {
            // 审核存疑
            articleVerifyRecord.setVerifyStatus(VerifyStatusEnum.WAIT.getStatus())
                    .setVerifyResult(VerifyResultEnum.IN_DOUBT.getDesc())
                    .setNeedManualVerify(YesOrNoEnum.YES.getCode());
        } else if (result == VerifyResultEnum.REJECT) {
            // 审核拒绝
            articleVerifyRecord.setVerifyResult(VerifyResultEnum.REJECT.getDesc())
                    .setRiskLevel(verifyResult.getRiskLevel())
                    .setRiskTips(verifyResult.getRiskTips())
                    .setRiskWords(verifyResult.getRiskWords())
                    .setRiskLabel(verifyResult.getLabels());
            checkResult = Boolean.FALSE;
        }
        articleVerifyRecordMapper.insert(articleVerifyRecord);
        return checkResult;
    }

    private VerifyResult getVerifyResult(String content) {
        TextVerifyModel textVerifyModel = new TextVerifyModel();
        textVerifyModel.setTextContent(content);
        textVerifyModel.setTextService(TextServiceEnum.CHAT_DETECTION.getService());
        ContentVerifyContext verifyContext = ContentVerifyContext.builder()
                .verifyType(VerifyTypeEnum.TEXT)
                .textVerifyModel(textVerifyModel)
                .build();
        verifyProcessor.contentVerify(verifyContext);
        return verifyContext.getVerifyResult();
    }
}
